package com.qiwo.bpm.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.qiwo.bpm.domain.FlowType;
import com.qiwo.bpm.service.FlowTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qiwo.bpm.dao.FunctionDao;
import com.qiwo.bpm.domain.FlowFunction;
import com.qiwo.bpm.service.FlowFunctionService;
import com.qiwo.common.base.CoreServiceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * <pre>
 * 流程功能
 * </pre>
 *  @author  chenwenchao
 *  @date 2021-04-01 16:53:20
 * <small> 2021-04-01 16:53:20 | chenwenchao</small>
 */
@Service
public class FlowFunctionServiceImpl extends CoreServiceImpl<FunctionDao, FlowFunction> implements FlowFunctionService {

    @Autowired
    private FlowTypeService flowTypeService;

    @Override
    public String getFunctions(Integer flowtype) {
        List<FlowType> fts = this.flowTypeService.getAllParentFlowTypes(flowtype);
        List<Long> typeIds = new ArrayList();
        for (FlowType ft : fts) {
            typeIds.add(ft.getId());
        }
        StringBuffer functions = new StringBuffer();

        Wrapper<FlowFunction> wrapper=new EntityWrapper<>();
        if(typeIds!=null&&typeIds.size()>0) {
            wrapper.in("flow_type", typeIds);
        }
        List<FlowFunction> flowfunctions = this.baseMapper.selectList(wrapper);
        int j = flowfunctions.size();
        for (int i = 0; i < j; i++) {
            FlowFunction flowFunction = (FlowFunction)flowfunctions.get(i);
            if (i != 0)
                functions.append(";");
            functions.append(flowFunction.getCode()).append(",").append(flowFunction.getName()).append(",")
                    .append(flowFunction.getChecked()).append(",")
                    .append("top".equals(flowFunction.getFlowType()) ? "pub" : "buss");
        }
        return functions.toString();
    }

    @Override
    public Boolean functionLegitimate(FlowFunction flowFunction) {
        Wrapper<FlowFunction> wrapper=new EntityWrapper<>();
        wrapper.eq("code",flowFunction.getCode());
        if (flowFunction.getId()!=null) {
            return  baseMapper.selectCount(wrapper)>0;
        } else {
            wrapper.ne("id",flowFunction.getId());
            return  baseMapper.selectCount(wrapper)>0;
        }
    }


}
